package com.stanyung.realtimeserver.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.alibaba.fastjson.JSON;

public class ChatProtocolEncoder implements ProtocolEncoder {

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		Packet packet = (Packet) message;

		byte[] bytes = packet.toBytes();
		IoBuffer buffer = IoBuffer.allocate(4 + bytes.length);
		buffer.setAutoExpand(true);
		buffer.putInt(bytes.length);
		buffer.put(bytes);
		buffer.flip();
		out.write(buffer);
		out.flush();
	}

	@Override
	public void dispose(IoSession session) throws Exception {

	}

}
